import { Ref, defineComponent, onMounted, reactive, ref } from "vue";
import classes from "./index.module.scss"
import Telescoping from "@/components/Telescoping";
import Table, { GridType } from "@/components/Table";
import { useEmiter } from "@/hooks/useEmiter";
import apiStore from "@/stores/apiStore";
import { WorkArea } from "@/components/WorkArea";
import { ConditionItemType, ToolsItemType } from "@/hooks/useElementFormItem";
import { useTable } from "@/hooks/useTable";
import { onEnterKeydown } from "@/hoc/onEnterDown";
import { PositionDialog, PostionTitleType } from "./module/position-dialog"
import { ElMessage } from "element-plus";
import { isSuccessCode, useElMessageBox } from "@Tea/utils";
import { PositionDetailsDialog, PostionDeatailTitleType } from "./module/positionDetail-dialog";

const Position = defineComponent({
  setup(props, ctx) {
    const tableName = "positionList"
    const { tableLoading, getSelected, commonSearch } = useTable(tableName)
    const { getPositioList, delPosition } = apiStore().api

    const visible = ref(false) // 弹框显示
    const dialogTitle = ref<PostionTitleType>("新增职位") // 弹框标题

    // 搜索条件
    const searchForm = reactive({
      positionCode: "",
      positionName: ""
    })

    // form
    const ruleForm = reactive<typeof searchForm>({
      positionCode: "",
      positionName: ""
    })
    
    /**
     * @vuese 查询
     */
    const searchData = async () => {
      commonSearch(getPositioList(searchForm))
    }

    // 操作成功
    const handleSuccess = (ctrlShow:Ref<boolean>) => {
      ctrlShow.value = false
      searchData()
    }

    /**
     * @use 新增
     */
    const add = () => {
      visible.value = true
      dialogTitle.value = "新增职位"
    }
    /**
     * @use 编辑
     */
    const edit = () => {
      const selectRow = getSelected()[0] as typeof searchForm
      if (selectRow) {
        Object.assign(ruleForm, selectRow)

        visible.value = true
        dialogTitle.value = "编辑职位"
      } else {
        ElMessage({
          message: '请选择一条数据',
          type: 'warning',
        })
      }
    }

    // 点击删除
    const deleltPoisition = () => {
      const selectRow = getSelected()[0] as typeof searchForm
      if (selectRow) {
        useElMessageBox({
          content: "确定要删除该数据吗？",
          thenCallback: async () => {
            try {
              tableLoading.value = true
              const { code, msg } = await delPosition(selectRow.positionCode)
              if (isSuccessCode(code)) {
                ElMessage({
                  message: '删除成功',
                  type: 'success',
                })
                handleSuccess(tableLoading)
              }
            } catch (e) {
              tableLoading.value = false
              console.log(e);
            }
          }
        })
      } else {
        ElMessage({
          message: '请选择一条数据',
          type: 'warning',
        })
      }
    };

    // 创建工具的配置
    const toolsList: ToolsItemType[] = [
      {
        type: "button", content: "新增", attr: {
          onClick: add
        }
      },
      {
        type: "button", content: "编辑", attr: {
          onClick: edit
        }
      },
      ,
      {
        type: "button", content: "删除", attr: {
          onClick: deleltPoisition
        }
      }
    ]
    // 创建搜索条件的配置
    const condition: ConditionItemType<typeof searchForm>[] = [
      {
        type: "text",
        vModel: searchForm,
        feild: "positionCode",
        label: "职位编码",
        col:6,
        attr: {
          placeholder: "职位编码",
          onClear: searchData,
          onKeydown:(e:KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      },
      {
        type: "text",
        feild:"positionName",
        vModel: searchForm,
        col: 6,
        label: "职位名称",
        attr: {
          placeholder: "职位名称",
          onClear: searchData,
          onKeydown:(e:KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      }
    ]
    // agGrid 配置项
    const gridAttr: GridType = {
      columnDefs: [
        { headerName: "职位编码",checkboxSelection:true, field: "positionCode", width: 250 },
        { headerName: "职位名称", field: "positionName", width: 250 },
      ],
      rowSelection:"single"
    }

    onMounted(() => {
      searchData()
    })

    return () => (
      <div class={`m-window m-fullBox p-right ${classes.positionList}`}>
        <div class="t-title">职位列表</div>
        <header class={`m-bottom ${classes.listHeader}`}>
          <WorkArea
            tools={toolsList}
            condition={condition}
            onSearch={searchData}
          >
          </WorkArea>
        </header>
        <Table
          v-loading={tableLoading.value}
          gridAttr={gridAttr}
          tableName={tableName}
          initPagination={false}
        ></Table>
        
        <PositionDialog
          visible={visible}
          title={dialogTitle.value}
          ruleForm={ruleForm}
          handleSuccess={() => handleSuccess(visible)}
        >
        </PositionDialog>
      </div>
    )
  },
})

const PositionDetail = defineComponent({
  setup(props, ctx) {
    const { tableName} = useEmiter("positionDetail")
    const { positionDetail ,delPositionMember} = apiStore().api
    const { mountSearch ,assginPaging, tableLoading,commonSearch, getSelected} = useTable(tableName)
    const visible = ref(false) // 弹框显示
    const dialogTitle = ref<PostionDeatailTitleType>("新增成员") // 弹框标题、
    // 搜索条件
    const searchForm = reactive({
      positionCode: "",
      positionName: "",
      memberName: ""
    })

    // form
    const ruleForm = reactive({
      positionCode: "",
      userId: "" as any as number
    })
    
    /**
     * @use 查询
     */
    const searchData = async () => {
      commonSearch(positionDetail(assginPaging(searchForm)))
    }

    /**
     * @use 删除
     */
    const onDelete = () => {
      const selectRow = getSelected()[0] as typeof searchForm & { id: number }
      if (selectRow) {
        useElMessageBox({
          content: "确定要删除该数据吗？",
          thenCallback: async () => {
            try {
              tableLoading.value = true
              const { code, msg } = await delPositionMember(selectRow.id)
              if (isSuccessCode(code)) {
                ElMessage({
                  message: msg,
                  type: 'success',
                })
                handleSuccess(tableLoading)
              }
            } catch (e) {
              tableLoading.value = false
              console.log(e);
          
            }
          }
        })
      } else {
        ElMessage({
          message: '请选择一条数据',
          type: 'warning',
        })
      }
    }

    // 创建工具的配置
    const toolsList: ToolsItemType[] = [
      {
        type: "button", content: "新增", attr: {
          onClick: () => visible.value = true
        }
      },
      {
        type: "button", content: "删除", attr: {
          onClick: onDelete
        }
      }
    ]
    // 创建搜索条件的配置
    const condition: ConditionItemType<typeof searchForm>[] = [
      {
        type: "text",
        vModel: searchForm,
        feild: "positionCode",
        label: "职位编码",
        col: 6,
        attr: {
          placeholder: "职位编码",
          onClear: searchData,
          onKeydown: (e: KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      },
      {
        type: "text",
        feild: "positionName",
        vModel: searchForm,
        col: 6,
        label: "职位名称",
        attr: {
          placeholder: "职位名称",
          onClear: searchData,
          onKeydown: (e: KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      },
      {
        type: "text",
        feild: "memberName",
        vModel: searchForm,
        col: 6,
        label: "成员名称",
        attr: {
          placeholder: "成员名称",
          onClear: searchData,
          onKeydown: (e: KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      }
    ]
    // agGrid 配置项
    const gridAttr: GridType = {
      columnDefs: [
        { headerName: "职位编码",checkboxSelection: true, field: "positionCode", width: 150 },
        { headerName: "职位名称", field: "positionName", width: 150 },
        { headerName: "成员名称", field: "memberName", width: 150 },
      ],
      rowSelection:"single"
    }

    // 操作成功
    const handleSuccess = (ctrlShow:Ref<boolean>) => {
      ctrlShow.value = false
      searchData()
    }

    onMounted(() => {
      mountSearch(searchData)
      searchData()
    })

    return () => (
      <div class={`m-window m-fullBox p-left ${classes.positionDetail}`} >
        <div class="t-title">职位详情</div>
        <header class={`m-bottom ${classes.detailHeader}`}>
          <WorkArea
            tools={toolsList}
            condition={condition}
            onSearch={searchData}
          >
          </WorkArea>
        </header>
        <Table
          v-loading={tableLoading.value}
          gridAttr={gridAttr}
          tableName={tableName}
        ></Table>
        <PositionDetailsDialog
          visible={visible}
          title={dialogTitle.value}
          ruleForm={ruleForm}
          handleSuccess={() => handleSuccess(visible)}
        >

        </PositionDetailsDialog>
      </div>
    )
  },
})

export default defineComponent({
  name: "positionManage",
  setup(props, ctx) {
    return () => <div class={`m-fullBox m-padding ${classes.positionManage}`}>
      <Telescoping
        firstConfig={{
          minWidth: "230px",
          maxWidth:"920px"
        }}
        v-slots={{
          firstNode: () => <Position />,
          secondNode: () => <PositionDetail/>
        }}
      >
      </Telescoping>
    </div>
  },
})